/*
 * This file is part of Plop Messenger.
 *
 * Plop Messenger is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 *  Plop Messenger is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with Plop Messenger.  If not, see <http://www.gnu.org/licenses/>.
 */
package pm.net;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;

import pm.Constantes;

public class PosteUDP implements Runnable {

	private List<PosteUDPListener> listeners = new ArrayList<PosteUDPListener>();
	private DatagramSocket socket;
	private Thread thread;

	public PosteUDP(int port) throws SocketException {
		socket = new DatagramSocket(port);
	}

	public void addListener(PosteUDPListener l) {
		listeners.add(l);
	}

	private void firePacketRecu(DatagramPacket packet) {
		for (PosteUDPListener l : listeners) {
			l.packetRecu(this, packet);
		}
	}
	
	public void removeListener(PosteUDPListener l) {
		listeners.remove(l);
	}

	@Override
	public void run() {
		while (true) {
			try {
				byte buffer[] = new byte[Constantes.BUFFER_SIZE];
				DatagramPacket packet = new DatagramPacket(buffer,
						Constantes.BUFFER_SIZE);
				socket.receive(packet);
				firePacketRecu(packet);
			} catch (IOException e) {
			}
		}
	}

	public void sendPacket(DatagramPacket packet) throws IOException{
		socket.send(packet);
	}
	
	public void start(){
		if(thread==null){
			thread = new Thread(this);
			thread.start();
		}
	}
}
